package demo_0421.hw;

public class TurtleRace {

    private static final int TOTAL_DISTANCE = 50; // 总赛程

    public static void main(String[] args) {
        Thread rabbit = new Thread(new Runnable() {
            @Override
            public void run() {
                race(0.5, 2, 10); // 兔子速度为0.5米/秒，每跑2米休息10秒
            }
        }, "Rabbit");

        Thread turtle = new Thread(new Runnable() {
            @Override
            public void run() {
                race(0.1, -1, -1); // 乌龟速度为0.1米/秒，不休息
            }
        }, "Turtle");

        rabbit.start();
        turtle.start();

        try {
            rabbit.join();
            turtle.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("比赛结束！");
    }

    private static synchronized void race(double speed, int restDistance, int restTime) {
        int distance = 0;
        while (distance < TOTAL_DISTANCE) {
            distance += speed;
            if (restDistance > 0 && distance >= restDistance) {
                try {
                    System.out.printf("%s 跑了 %d 米，现在休息...\n", Thread.currentThread().getName(), (int)distance);
                    Thread.sleep(restTime * 1000);
                    distance -= restDistance; // 休息后从当前位置继续
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.printf("%s: %d 米\n", Thread.currentThread().getName(), (int)distance);
            try {
                Thread.sleep(1000); // 每秒更新一次距离
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.printf("%s 完成比赛！\n", Thread.currentThread().getName());
    }
}

